//
// Description: 5895. 获取单值网格的最小操作数
// Created by Loading on 2021/10/10.
//

#include <bits/stdc++.h>

using namespace std;

int minOperations(vector<vector<int>> &grid, int x) {
    vector<int> vec;
    for (auto &v : grid) {
        for (auto &num : v) {
            vec.emplace_back(num);
        }
    }
    sort(vec.begin(), vec.end());

    // 向中间的数靠近
    int avg = vec[vec.size() / 2];
    int res = 0;
    for (auto &num : vec) {
        // 不可以到达
        if ((num - avg) % x != 0) {
            return -1;
        } else {
            res += abs(num - avg) / x;
        }
    }

    return res;
}

int main() {
    vector<vector<int>> grid = {{1, 2},
                                {3, 4}};
    int x = 1;
    int res = minOperations(grid, x);
    cout << res << endl;

    return 0;
}